#include "tabellaicone.h"
//
/*  Save file as tabellaicone.cpp  */
/*  incomming class name TabellaIcone */
//


#include "strutturaicone.h"



TabellaIcone::TabellaIcone( QWidget * parent )
	: QTableWidget( parent )
{
	   
     setMinimumSize (580,420) ;
	   linenummers = NumerazioneIconeValidate();
	   onloading = true;
     QTableWidget::setColumnCount(12);
	   QTableWidget::setRowCount( linenummers.size() );
	   setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding ); 
	   QStringList nomi = QStringList() << tr("Icona") << tr("Ic.Bn") << tr("Nr.") << tr("Nr.Ti") << tr("Cat.") << tr("Car.") << tr("Italiano") << tr("Tedesco") << tr("Francese") << tr("Inglese") << tr("Fonts") << tr("Riserva o note");
	   traduzioneNumero = TraduzioneIconeValidate(); 
     Updates.clear();
	
	
	   setHorizontalHeaderLabels(nomi);
	   int linee = -1;
	    QMapIterator <int,int> d(linenummers);
	       while (d.hasNext()) {
						d.next();
					  linee++;
					  IcoLine Iconas;
										Iconas.nummer = qMakePair(d.key(),d.value());
					           QPixmap onreso = QPixmap(QString::fromUtf8(":/ico/img/icone/att_%1.png").arg(d.value()));
					            Iconas.set_pics(onreso);
					             WrittelnLine(Iconas,linee);
					  
				 }
	  setContextMenuPolicy(Qt::DefaultContextMenu);
	  resizeColumnToContents ( 0 );
				 resizeColumnToContents ( 1 );
				 resizeColumnToContents ( 2 );
				 resizeColumnToContents ( 3 );
				 resizeColumnToContents ( 4 );
				 resizeColumnToContents ( 5 );
	  resizeRowsToContents();
	  ///////UpdateFromFiles();
		setSortingEnabled(false);
		setSelectionBehavior(QAbstractItemView::SelectRows);
		setSelectionMode ( QAbstractItemView::SingleSelection ); 
    setAlternatingRowColors(true);
		setItemDelegate(new AlphaDelegate(this,QStringList()));
		onloading = false;
		connect(this, SIGNAL(cellChanged(int,int)),this, SLOT(NewDataSet(int,int)));
				 
				 //////
				 
}


void TabellaIcone::PrintItems()
{
	 ModelSwap Xmodel;
	           Xmodel.set(this);
	 
	  QTextDocument *xdoc = Xmodel.TabletoDom();
    TextPrinter *textprinter_ = new TextPrinter(this);
    textprinter_->setHeaderSize(3);
	  textprinter_->setLeftMargin(11);
	  textprinter_->setRightMargin(2);
    textprinter_->preview(xdoc, tr("Anteprima di stampa"));
	
}

void TabellaIcone::OtherIconSet()
{
    QAction *invoice = qobject_cast<QAction *>(sender());
    const int xrow = invoice->data().toInt();
	  if (xrow > -1) {
			
			       QModelIndex index = model()->index(xrow,0);
						 IcoLine dd = model()->data(index,Qt::UserRole).value<IcoLine>();
			       QString file = QFileDialog::getOpenFileName( this, tr( "Scegli una immagine..." ), QString(setter.value("LastDir").toString()) ,"*");
               if ( file.isEmpty() ) {
               return;
               }
               QPixmap ssets(file); 
							 if (ssets.isNull()) {
								 QMessageBox::critical( this, tr( "Alert! image format." ), tr( "Unable to render file as image" )); 
								 return;
							 }
							 
							 dd.set_pics(ssets);
							 WrittelnLine(dd,xrow);
							 
							 
			
		}
	
    
}


void TabellaIcone::contextMenuEvent ( QContextMenuEvent * e )
{
	  const int OnLineClick = currentRow();
	  if (OnLineClick > -1) {
			       QModelIndex index = model()->index(OnLineClick,0);
						 IcoLine dd = model()->data(index,Qt::UserRole).value<IcoLine>();
			
			
			       QMenu *TContext = new QMenu();
			       TContext->addAction(tr( "Anteprima di stampa" ), this , SLOT( PrintItems() ) );
			       TContext->addAction(tr( "Esporta come file" ), this , SLOT( ExportAsFile() ) );
		         TContext->addAction(tr( "Importa da file" ), this , SLOT( ImportFromFile() ) );
			       TContext->addSeparator ();
			       TContext->addAction(tr( "Esporta icone per web colori." ), this , SLOT( Esportapicweb_color() ) );
			       TContext->addAction(tr( "Esporta icone per web B/N." ), this , SLOT( Esportapicweb_bn() ) );
			       TContext->addSeparator ();
			       TContext->addAction(tr( "Aggiorna da file lista icone ti turismo xml." ), this , SLOT( UpdateFromFiles() ) );
			       TContext->addSeparator ();
			       TContext->addAction(tr( "Apri da risorse Applicazione salvataggio applicazione versione %1" ).arg(_PICO_VERSION_), this , SLOT( LoadFromResource() ) );
			       TContext->addSeparator ();
			
						 ActionswapIcon= new QAction(tr("Cambia icona a ID %1").arg(dd.id()),this);
             ActionswapIcon->setIcon(QIcon( dd.pix() ));
			       ActionswapIcon->setData(OnLineClick);
             connect(ActionswapIcon, SIGNAL(triggered()), this,  SLOT(OtherIconSet()));
			       TContext->addAction(ActionswapIcon);
						 
						 
			         TContext->exec(QCursor::pos());
               TContext->deleteLater();
               delete TContext;
		}
}


void TabellaIcone::closeEvent( QCloseEvent* e )
{
	
	  if (unsaved) {
			
			QString msgDB =tr("Vuoi salvare i dati modificati?");
      int removeyes = QMessageBox::question(this, tr("Prego confermare!"),msgDB,
                                                            tr("&Si"), tr("&No"),
                                                             QString(),8888,9999);
			if (removeyes == 0) {
				SaveString();
				emit SaveAll();
			}
			
			
		}
	
	
}


void TabellaIcone::OpenFromStreamString( const QString data )
{
	onloading = true;
	TabIcone DDt = OpenTabelicon(data);
	created = DDt.creato;
	for (int i=0; i<DDt.all_lines.size(); i++) {
		IcoLine Celinea = DDt.all_lines[i];
		 WrittelnLine(Celinea,Celinea.id() - 1); 
	}
	onloading = false;
	unsaved = false;
}

void TabellaIcone::ImportFromFile()
{
QString fixfile = QFileDialog::getOpenFileName(this, tr("Importa - Apri file"),
	                          QCoreApplication::applicationDirPath(),
	                                         "Attribute_Tourist_file (*.hcad)" );
	
	FileOpener(fixfile);
	unsaved = true;
}

void TabellaIcone::FileOpener( const QString fixfile )
{
	  onloading = true;
	  quint32 magic, version;
	  
    if (!fixfile.isEmpty()) {
			      QFile f(fixfile); 
						if (f.exists()) {
												if (f.open(QIODevice::ReadOnly)) {
														QDataStream ds(&f);
														/* place header */
														ds.setVersion(QDataStream::Qt_4_0);
														ds >> magic;
														if ( (quint32)TabIcone::MAGICNUMBER != magic ) {
															qDebug() << "######## MAGICNUMBER not ok  ";
															f.close();
															onloading = false;
															return;
														}
														ds >> version;
														if ( (quint32)TabIcone::VERSION != version ) {
															qDebug() << "######## VERSION not ok  ";
															f.close();
															onloading = false;
															return;
														}
														/* place header */
														ds >> created;
														IcoLine Celinea;
														while (!ds.atEnd())  {
																	ds >> Celinea;
																	WrittelnLine(Celinea,Celinea.id() - 1); 
																}
													f.close();
												}
						}
			
		}
		onloading = false;
}


QString TabellaIcone::SaveString()
{
	TabIcone ddin;
		                   for (int i=0; i<model()->rowCount(); i++) {
												    QModelIndex index = model()->index(i,0);
												    IcoLine dd = model()->data(index,Qt::UserRole).value<IcoLine>();
												    ddin.all_lines.append(dd);
											 }
											 
	return SaveTabelicon(ddin);
}

void TabellaIcone::NewDataSet( const int riga , const int linea )
{
	if (onloading) {
		return;
	}
	onloading = true;
	IcoLine ddo = item(riga,0)->data(Qt::UserRole).value<IcoLine>();
	//////////qDebug() << "NewDataSet   " << riga;
	///////qDebug() << "NewDataSet   " << ddo.id();
	//////////qDebug() << "NewDataSet it   " << item(riga,6)->text();
	ddo.it = item(riga,6)->text();
	ddo.de = item(riga,7)->text();
	ddo.fr = item(riga,8)->text();
	ddo.en = item(riga,9)->text();
	ddo.info.clear();
	ddo.info.append(item(riga,10)->text());
	ddo.info.append(item(riga,11)->text());
	ddo.info.append("end.");
	ddo.cate = item(riga,4)->text().toInt();
	ddo.update_rid(item(riga,3)->text().toInt());
	ddo.chars = QChar(item(riga,5)->text().at(0));
	ddo.close();
	item(riga,0)->setData(Qt::UserRole,ddo);
	onloading = false;
	unsaved = true;
}
QList<QTableWidgetItem *> TabellaIcone::selector( const int riga ) 
{
	QList<QTableWidgetItem *> ActiveList;
	ActiveList.clear();
	for (int i = 0; i < model()->columnCount(); ++i) {
	QTableWidgetItem *Selectionx = item(riga,i);
	ActiveList.append(Selectionx);
	}
	return ActiveList;
}



void TabellaIcone::ExportAsFile()
{
	 QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                            QCoreApplication::applicationDirPath(),
                            tr("Attribute_Tourist_file (*.hcad)"));
	
			if (!fileName.isEmpty() ) {
        if (!fileName.endsWith(".hcad")) {
            fileName.append(".hcad");
        }
				TabIcone ddin;  /* only save time created ! */
        QFile f( fileName );
        if ( f.open( QIODevice::WriteOnly  ) )
        {
        	QDataStream ds(&f);
						/* place header */
						ds.setVersion(QDataStream::Qt_4_0);
						ds << (quint32)TabIcone::MAGICNUMBER;
						ds << (quint32)TabIcone::VERSION;
						ds << ddin.creato;
						
											for (int i=0; i<model()->rowCount(); i++) {
												    QModelIndex index = model()->index(i,0);
												    IcoLine dd = model()->data(index,Qt::UserRole).value<IcoLine>();
												    ds << dd;
											}
						
						f.close();
        }
				
			}
	
}










void TabellaIcone::Esportapicweb_color()
{
	QString dir = QFileDialog::getExistingDirectory(this, tr("Seleziona la cartella"),
                                                 QCoreApplication::applicationDirPath(),
                                                 QFileDialog::ShowDirsOnly
                                                 | QFileDialog::DontResolveSymlinks);
				                
											for (int i=0; i<model()->rowCount(); i++) {
												    QModelIndex index = model()->index(i,0);
												    IcoLine dd = model()->data(index,Qt::UserRole).value<IcoLine>();
														QPixmap current = dd.pix();
														current.save(dir+"/att_"+QString("%1.png").arg(dd.id()),"PNG",100);
											}
}


void TabellaIcone::Esportapicweb_bn()
{
	QString dir = QFileDialog::getExistingDirectory(this, tr("Seleziona la cartella"),
                                                 QCoreApplication::applicationDirPath(),
                                                 QFileDialog::ShowDirsOnly
                                                 | QFileDialog::DontResolveSymlinks);
				                
											for (int i=0; i<model()->rowCount(); i++) {
												    QModelIndex index = model()->index(i,0);
												    IcoLine dd = model()->data(index,Qt::UserRole).value<IcoLine>();
														QPixmap current = dd.pixbn();
														current.save(dir+"/att_"+QString("%1.png").arg(dd.id()),"PNG",100);
											}
}



void TabellaIcone::UpdateFromFiles()
{
	QString now = QFileDialog::getExistingDirectory(this, tr("Seleziona la cartella"),
                                                 QCoreApplication::applicationDirPath(),
                                                 QFileDialog::ShowDirsOnly
                                                 | QFileDialog::DontResolveSymlinks);
	
	
	 QDir dir( now );
   if (dir.exists())
   {
      const QFileInfoList list = dir.entryInfoList();
      QFileInfo fi;
      for (int l = 0; l < list.size(); l++)
      {
         fi = list.at(l);
         if (fi.isDir() && fi.fileName() != "." && fi.fileName() != "..") {
         } else if (fi.isFile() && fi.fileName().endsWith(".xml")  ) {
					 
                Parsefile(fi.absoluteFilePath());
         } 
        
      }
   }
	 
	 if (Updates.size() > 0) {
		    
		    QMapIterator <int,IcoLine> d(Updates);
		    int cope = -1;
	       while (d.hasNext()) {
					 d.next();
					 IcoLine uso = d.value();
					//////////// WrittelnLine(uso,d.key() - 1 );
					  cope++;
					  qDebug() << "### agg " << cope << " " << d.key();
					  WrittelnLine(uso,d.key() - 1 );
					  
				 }
	 } 
	 
	 unsaved = true;
}


void TabellaIcone::WrittelnLine( IcoLine Iconas , const int line ) 
{
	
	
	
	
	    QTableWidgetItem *iet0 = new QTableWidgetItem();
			iet0->setData(Qt::DecorationRole,Iconas.pix());
	    iet0->setFlags ( Qt::ItemIsSelectable | Qt::ItemIsEnabled );
	    iet0->setData(Qt::UserRole,Iconas);
	
	    QTableWidgetItem *iet1 = new QTableWidgetItem();
			iet1->setData(Qt::DecorationRole,Iconas.pixbn());
	    iet1->setFlags ( Qt::ItemIsTristate );
	
					 
					           QTableWidgetItem *ieta = new QTableWidgetItem(QString::number(Iconas.id()));
					           QTableWidgetItem *ietb = new QTableWidgetItem(QString::number(Iconas.rid()));
					           
	                   ieta->setFlags ( Qt::ItemIsTristate );
	                   //////////ietb->setFlags ( Qt::ItemIsSelectable | Qt::ItemIsEnabled );
	
					
					                 setItem(line,0,iet0);
	                         setItem(line,1,iet1);
					                 setItem(line,2,ieta); 
					                 setItem(line,3,ietb); 
					                 setItem(line,4,new QTableWidgetItem(Iconas.categ())); 
					                 setItem(line,5,new QTableWidgetItem(QString(Iconas.chars))); 
					                 setItem(line,6,new QTableWidgetItem(Iconas.it)); 
													 setItem(line,7,new QTableWidgetItem(Iconas.de)); 
													 setItem(line,8,new QTableWidgetItem(Iconas.fr)); 
													 setItem(line,9,new QTableWidgetItem(Iconas.en)); 
													 setItem(line,10,new QTableWidgetItem(Iconas.info.at(0))); 
													 
													 QTableWidgetItem *lastitem = new QTableWidgetItem(Iconas.info.at(1));
													 lastitem->setToolTip ( QString("Info size %1").arg(Iconas.info.size()));
													 
													 setItem(line,11,lastitem); 
													 
					
	
	
}

void TabellaIcone::LoadFromResource()
{
	
	FileOpener(":/img/aggiornato_ultimo.hcad");  
	unsaved = true;
}



void TabellaIcone::Parsefile( const QString fullFileName )
{
	
	qDebug() << "### Parsefile " << fullFileName;
	
	
    QString errorStr;
    int errorLine, errorColumn, position;
    QFile f( fullFileName );
	  if ( !f.exists(fullFileName) ) {
    return;   
    }
    if(!f.open(QIODevice::ReadOnly)) {
    return;
    }
		QDomDocument doc;
    /* no namen space ! */
    if (!doc.setContent(&f,false, &errorStr, &errorLine, &errorColumn)) {
			
			qDebug() << "### non conforme " << fullFileName;
			
    return;
    }
		 QDomElement root = doc.documentElement();
	  QDomElement d1 = root.firstChildElement("S:Body");
	  QDomElement d2 = d1.firstChildElement("ns2:getFatAttributesByItemTypeResponse");
	  /////////QDomElement r = d2.firstChildElement("return"); 
		
		    QDomNode chi = d2.firstChild();
                   while ( !chi.isNull() ) {
										 
										 
										 
                       if ( chi.isElement() ) {
												    const QDomElement e = chi.toElement();
												    qDebug() << "### e.tagName() " << e.tagName();
												 
												 if (e.tagName() == "return") {
													 const int idtii = e.firstChildElement("attributeId").text().toInt();
													 int numero_mio = 0;
													 numero_mio = traduzioneNumero.value(idtii);
													 
													 qDebug() << "### dummy.it" << idtii << " " << numero_mio;
													  
													 
													 IcoLine dummy;
													 dummy.nummer = qMakePair(numero_mio,idtii);
													 QPixmap onreso = QPixmap(QString::fromUtf8(":/ico/img/icone/att_%1.png").arg(idtii));
					                 dummy.set_pics(onreso);
													    
													   	dummy.it = e.firstChildElement("description_I").text();
															dummy.de = e.firstChildElement("description_D").text();
															dummy.fr = e.firstChildElement("description_F").text();
															dummy.en = e.firstChildElement("description_E").text();
													 
													 ///////qDebug() << "### dummy.it" << dummy.it << " " << numero_mio;
													 
													 
							              if (numero_mio > 0 && numero_mio < model()->rowCount() ) {
													  Updates.insert(numero_mio,dummy);
														}
												 }
												 
											 }
											 
											 chi = chi.nextSiblingElement("return"); 
										 }
}















AlphaDelegate::AlphaDelegate(QObject *parent , QStringList external )
		: QItemDelegate(parent)
{
  External_Name = external;   
}


QWidget *AlphaDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem&,
                                       const QModelIndex &index) const
{
	if (index.column() == 4 ) {
		QSpinBox *editor = new QSpinBox(parent);
		editor->setMaximum(3);
		return editor;
	}
	
	if (index.column() == 3 ) {
		QSpinBox *editor = new QSpinBox(parent);
		editor->setMaximum(5000);
    editor->setMinimum(100);
		return editor;
	}
  
	QLineEdit *editor = new QLineEdit(parent);
	//create a completer with the strings in the column as model.
	QStringList allStrings;
	for (int i = 1; i<index.model()->rowCount(); i++) {
		QString strItem(index.model()->data(index.sibling(i, index.column()), Qt::EditRole).toString());
		if (!allStrings.contains(strItem))
			allStrings.append(strItem);
	}
    for (int o = 1; o<External_Name.size(); o++) {
        allStrings.append(External_Name.at(o));
    }
	QCompleter *autoComplete = new QCompleter(allStrings);
	editor->setCompleter(autoComplete);
	connect(editor, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor()));
	return editor;
}



void AlphaDelegate::commitAndCloseEditor()
{
	QLineEdit *editor = qobject_cast<QLineEdit *>(sender());
	emit commitData(editor);
	emit closeEditor(editor);
}


void AlphaDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
	QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
	if (edit) {
		edit->setText(index.model()->data(index, Qt::EditRole).toString());
	}
	
	else {
		QSpinBox *dedit = qobject_cast<QSpinBox *>(editor);
		if (dedit) {
            QString dax = index.model()->data(index, Qt::EditRole).toString().trimmed();
			      dedit->setValue(dax.toInt());
		}
	}
	
	
}




void AlphaDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                   const QModelIndex &index) const
{
	QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
	if (edit) {
		model->setData(index, edit->text());
	}
	else {
		QSpinBox *dedit = qobject_cast<QSpinBox *>(editor);
		if (dedit) {
			 model->setData(index, dedit->text());
		}
	}
}



/* delegate end ########################################################################################*/














